import {
  Button,
  Form,
  Icon,
  ImgDefault,
  Input,
  InputNumber,
  Menu,
  message,
  Modal,
  Popover,
  Select,
  Space,
  Table,
  Tag,
  Tooltip
} from "@bytedance/mona-ui"
import type { ColumnProps } from "@bytedance/mona-ui/es/components/table"
import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from "react"

import AutoPage from "./autoHome/autoPage"

import "./autoClass.scss"

import moment from "moment"

import { useAppDispatch, useAppSelector } from "~store"
import {
  getDlyUserInfoAction,
  setAutoSetCounterListStor,
  setAutoSetCounterListStorAndRun
} from "~store/controller/autoCounps"

import { generateRandomString } from "../../../jinritemaiCopyGoods/copyDataFomate"
// import type { autoCounpsType } from "~store/controller/autoCounps"
import LoginDlyUser from "../loginDlyUser"
import {
  aoutCoup,
  autoCoupStart,
  saveRunDentTime
} from "./autoHome/autoCoupFunc"
import GoodsTable from "./goodsTable"
import SmsOptions from "./smsOptions"

const ossurl = process.env.PLASMO_PUBLIC_CN_OSS

let editIndex: number = -1
function AutoSetCoupon(props: any) {
  const [addAutoCoupStatus, setAddAutoCoupStatus] = useState(false)
  interface ColumnPropsType {
    id: string
    index: number
    name: string
    discountType: number
    createBeforConf: {
      createBefor: number
      sendTimeActivet: number | string
      sendNumActivet: number | string
      useNum: number | string
    }
    isTopActivet: boolean
    MPTime: number | string
    sort: number
    geveTimeDateConf: {
      selectGeveTimetype: string
      geveTimeDate: string
    }
    valid_period: number | string
    goodsScope: number
    couponGoodsNum: number | string
    creditConf: {
      credit: string | number
      threshold: number | string
      discount: number | string
    }

    total_amount: number | string
    max_apply_times: number | string
    getSelectGoods: object[]
    status: number | string
    runScususe: object[]
    getTime: [number, number]
    errmsg: string | undefined
  }
  const [modowType, setModowType] = useState<"add" | "copy" | "edit">("add")
  const [editConfigData, setEditConfigData] = useState<any>(null)

  useEffect(() => {
    if (!addAutoCoupStatus) {
      setEditConfigData(null)
      setModowType("add")
    }
  }, [addAutoCoupStatus])
  function SortCom(props: any) {
    const [sortStatus, setSortStatus] = useState(false)
    const { record, onBlurf } = props
    if (!record) return null
    const [getOurter, setGetOurter] = useState(record)
    return (
      <>
        {!sortStatus ? (
          <Space>
            <span>{record.sort + 1}</span>
            <Button
              type="link"
              size="small"
              icon={<Icon type="EditIcon"></Icon>}
              onClick={() => {
                setSortStatus(true)
              }}></Button>
          </Space>
        ) : (
          <Space>
            <InputNumber
              value={getOurter.sort + 1}
              onChange={(e: any) => {
                getOurter.sort = e
                console.log("设置修改", getOurter)
                // autoSetCounterList.sort((a, b) => a.sort - b.sort)
                // setAutoSetCounterList([...autoSetCounterList])
                setGetOurter({ ...getOurter })
              }}
              size="small"
              onBlur={() => {
                console.log("失去焦点2")
                setSortStatus(false)
                onBlurf && onBlurf(getOurter)
              }}
              min={1}
              step={1}></InputNumber>
          </Space>
        )}
      </>
    )
  }
  const columnsAllTiles: ColumnProps<ColumnPropsType>[] = [
    {
      title: "序号",
      // dataIndex: 'sort',
      align: "center",
      width: 60,
      render: (text, record, index) => {
        return index + 1
      },
      fixed: "left"
    },
    {
      title: "状态",
      // dataIndex: 'MPTime',
      width: 160,
      align: "center",
      render: (text, record, index) => {
        switch (record.status) {
          case 0:
            return <Tag.Status type="warn">未开始</Tag.Status>
          case 1:
            return (
              <Space direction="vertical" size={0}>
                <Tag.Status>进行中</Tag.Status>
                创建进度
              </Space>
            )
          case 2:
            return (
              <Space direction="vertical" size={0}>
                <Tag.Status type="success">已完成</Tag.Status>
                <Button
                  type="link"
                  onClick={() => {
                    console.log("查看详情")
                    console.log("显示成功失败商品")
                    setShowAutoCoupList(true)
                    setLockGoodsConter(true)
                    setAddCouponConfig(record)
                  }}>
                  查看详情
                </Button>
              </Space>
            )
          case 3:
            return (
              <Space direction="vertical" size={0}>
                <Tag.Status type="error">创建失败</Tag.Status>
              </Space>
            )
          case 4:
            return <Tag.Status type="cancel">取消创建</Tag.Status>
          case 11:
            return <Tag.Status type="cancel">领取结束时间已过期</Tag.Status>
          case 7:
            return <Tag.Status color="#5A34B5">正在运行,等待创建</Tag.Status>

          case 6:
            return (
              <Space direction="vertical" size={0}>
                <Tag.Status type="success">部分商品完成</Tag.Status>
                <Button
                  type="link"
                  onClick={() => {
                    console.log("查看详情")
                    console.log("显示成功失败商品")
                    setShowAutoCoupList(true)
                    setLockGoodsConter(true)
                    setAddCouponConfig(record)
                  }}>
                  查看详情
                </Button>
              </Space>
            )
          case 9:
            return (
              <Space direction="vertical" size={0}>
                <Tag.Status>部分商品进行中</Tag.Status>
                {/* <Button type="link" onClick={() => {
                                console.log('查看详情')
                                console.log('显示成功失败商品')
                            }}></Button> */}
              </Space>
            )
          case 13:
            return (
              <Space direction="vertical" size={0}>
                <Tag.Status type="error">不可创建，等待重试</Tag.Status>
                <span>{record?.errmsg}</span>
                {/* <Button type="link" onClick={() => {
                                console.log('查看详情')
                                console.log('显示成功失败商品')
                            }}></Button> */}
              </Space>
            )
          default:
            return "未知"
        }
      }
    },
    {
      title: "领取时间",
      // dataIndex: 'geveTimeDate',
      align: "center",
      width: 160,
      render: (text, record, index) => {
        // let nuix = record.geveTimeDateConf.selectGeveTimetype === '0' ? '小时' : '天'

        const st = moment(record.getTime[0] * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        )
        const end = moment(record.getTime[1] * 1000).format(
          "YYYY-MM-DD HH:mm:ss"
        )
        return (
          <Space direction="vertical" size={0}>
            <span>{st}</span>
            <span>{end}</span>
          </Space>
        )
        // return `${st} - ${end}`
      }
    },
    {
      title: "使用时间",
      // dataIndex: 'valid_period',
      align: "center",
      width: 120,
      render: (text, record, index) => {
        return "开始后 " + record.valid_period + "天"
      }
    },
    {
      title: "范围",
      // dataIndex: 'goodsScope', // 每个券活动商品数
      align: "left",
      width: 160,
      render: (text, record, index) => {
        if (record.goodsScope === 2) {
          return "全店商品"
        }
        return (
          <Space direction="vertical" align="start" size={0}>
            <span>指定商品: 每个券{record.couponGoodsNum}商品</span>
            <span>待处理商品: {record.getSelectGoods?.length}</span>
            <Button
              type="link"
              onClick={() => {
                let edindexa
                autoSetCounterList.forEach((resas, idnex) => {
                  if (resas.id === record.id) {
                    edindexa = idnex
                  }
                })
                editIndex = edindexa
                setShowAutoCoupList(true)
                setAddCouponConfig(record)
              }}>
              查看商品
            </Button>
          </Space>
        )
      }
    },
    {
      title: "优惠类型",
      // dataIndex: 'goodsScope', //优惠券前缀
      width: 150,
      render: (text, record, index) => {
        let retoutitle
        if (record.discountType === 1) {
          retoutitle = `立减${record.creditConf.credit}元`
        }
        if (record.discountType === 2) {
          retoutitle = `满${record.creditConf.threshold}元 减${record.creditConf.credit}元`
        }
        if (record.discountType === 3) {
          retoutitle = `打${record.creditConf.discount}折`
        }

        return (
          <Space direction="vertical" align="start" size={0}>
            <span>{retoutitle}</span>
            <span>发放: {record.total_amount}张</span>
            <span>限领: {record.max_apply_times}张</span>
          </Space>
        )
      },
      align: "left"
    },
    {
      title: "创建时机",
      // dataIndex: 'createBefor',
      align: "center",
      width: 200,
      render: (text, record, index) => {
        if (!record.createBeforConf) return null
        return record.createBeforConf.createBefor === 1
          ? `领取时间结束前${record.createBeforConf.sendTimeActivet}分钟`
          : record.createBeforConf.createBefor === 2
          ? `优惠券领取剩余${record.createBeforConf.sendNumActivet}张`
          : record.createBeforConf.createBefor === 4
          ? `使用${record.createBeforConf.useNum}张`
          : `时间结束前${record.createBeforConf.sendTimeActivet}分钟或领取剩余${
              record.createBeforConf.sendNumActivet
            }张${
              record.createBeforConf.useNum
                ? `或使用${record.createBeforConf.useNum}张`
                : ""
            }`
      }
    },
    {
      title: "优惠券优先",
      // dataIndex: 'createBefor',
      align: "center",
      width: 85,
      render: (text, record, index) => {
        return record.isTopActivet ? "是" : "否"
      }
    },
    // {
    //     title: '任务巡查时间',
    //     // dataIndex: 'MPTime',
    //     align: "center",
    //     width: 95,
    //     render: (text, record, index) => {
    //         return record.MPTime + '分钟'
    //     },
    // },
    {
      title: "操作",
      // dataIndex: 'MPTime',
      width: 170,
      align: "center",
      fixed: "right",
      render: (text, record, index) => {
        return (
          <Space>
            <Button
              type="link"
              icon={<Icon type="CopyIcon"></Icon>}
              onClick={() => {
                console.log("打开新增页面")
                setModowType("copy")
                setAddAutoCoupStatus(true)
                setEditConfigData(record)
              }}>
              复制
            </Button>
            <Button
              type="link"
              icon={<Icon type="EditIcon"></Icon>}
              onClick={() => {
                console.log("打开编辑页面")
                editIndex = index
                setModowType("edit")
                setAddAutoCoupStatus(true)
                setEditConfigData(record)
              }}
              disabled={record.status !== 0}>
              编辑
            </Button>
            <Button
              type="link"
              danger
              style={{
                color: "red"
              }}
              icon={<Icon type="DeleteIcon"></Icon>}
              onClick={() => {
                Modal.warning({
                  title: "警告",
                  content: "删除任务后不可恢复，是否继续？",
                  onOk: (clear) => {
                    // console.log('删除任务列表')
                    const copySendData = JSON.parse(
                      JSON.stringify(autoSetCounterList)
                    )
                    copySendData.splice(index, 1)
                    setAutoSetCounterList(copySendData)
                    clear()
                  }
                })
              }}
              // disabled={record.status === 1}
            >
              删除
            </Button>
          </Space>
        )
      }
    }
  ]
  type ChildMethods = {
    // 子组件暴露给父组件的方法
    someMethod: () => void
    getSelectGoods: () => void
  }
  const getInfoCoupListData = () => {
    // localStorage.get('autoSetCoupon', JSON.stringify(listDataStr))
    try {
      const listDataStr: any = localStorage.getItem("autoSetCoupon")
      const listData = JSON.parse(listDataStr)
      // console.log('listData', listData)
      return listData || []
    } catch (error) {
      // console.log('解析失败', error)
      return []
    }
  }
  const autoRef = useRef<ChildMethods>(null)
  const [showAutoCoupList, setShowAutoCoupList] = useState(false)
  const [addCouponConfig, setAddCouponConfig] = useState<any>({})
  const selectGoodsdRef = useRef<ChildMethods>(null)
  const dispatch = useAppDispatch()

  function setAutoSetCounterList(data: any) {
    data.forEach((res) => {
      res.id =
        res.id ||
        generateRandomString(8) +
          String(Date.now()).substr(5) +
          String(Math.random()).substr(2, 4)
      res.createTime = res.createTime || new Date().getTime()
    })
    dispatch(setAutoSetCounterListStorAndRun(data))
  }
  const autoSetCounterList: any =
    useAppSelector((state) => state.autoCounps.autoSetCounterList) || []
  const addnewPrd: any = useAppSelector((state) => state.autoCounps.addnewPrd)
  const isBuyStatus = useAppSelector(
    (state) => state.jinritemaiProduct.isBuyStatus
  )
  const dlyUserBuyAutoInfo: any = useAppSelector(
    (state) => state.autoCounps.dlyUserBuyAutoInfo
  )
  // console.log('购买信息', dlyUserBuyAutoInfo)
  // const [autoSetCounterList, setAutoSetCounterList] = useState(getInfoCoupListData())
  // console.log('autoSetCounterList', autoSetCounterList)
  // useEffect(() => {
  //     console.log('开始推送自动设置配置', autoSetCounterList)
  //     autoSetCounterList.forEach(res => {
  //         res.id = res.id || generateRandomString(8) + String(Date.now()).substr(5) + String(Math.random()).substr(2, 4)
  //         res.createTime = res.createTime || new Date()
  //     })
  //     localStorage.setItem('autoSetCoupon', JSON.stringify(autoSetCounterList))
  //     aoutCoup(autoSetCounterList)
  //     // dispatch(setAutoSetCounterListStor(autoSetCounterList))
  // }, [autoSetCounterList])

  const [lockGoodsConter, setLockGoodsConter] = useState(false)

  const [runTimeStop, setRunTimeStop] = useState(getRunTimeSters())
  function getRunTimeSters() {
    const getRunTimeStaturTimes: any = localStorage.getItem("runTimeStaturTime")
    if (getRunTimeStaturTimes && !Number.isNaN(Number(getRunTimeStaturTimes))) {
      return getRunTimeStaturTimes
    } else {
      localStorage.setItem("runTimeStaturTime", "0.5")
      return 0.5
    }
  }
  useEffect(() => {
    console.log("通知到后台缓存", runTimeStop)
    saveRunDentTime(runTimeStop)
  }, [runTimeStop])

  function getMenuterter() {
    const gterOuter = localStorage.getItem("contmenus")
    if (gterOuter) {
      try {
        const getJson = JSON.parse(gterOuter)
        if (getJson && getJson.length > 0) {
          return getJson
        }
      } catch (error) {
        return [
          {
            name: "全部",
            key: "all"
          }
        ]
      }
    }
    return [
      {
        name: "全部",
        key: "all"
      }
    ]
  }

  const [menulistData, setMenulistData] = useState<any[]>(getMenuterter())
  const [selectMunu, setSelectMenu] = useState("all")
  const [addConter, setAddConter] = useState(false)
  const [addMunStext, setAddMunStext] = useState("")
  const [selecteCOnterKeys, setSelecteCOnterKeys] = useState<any[]>([])
  const [showLoginContent, setShowLoginContent] = useState(cheackLogin())
  function cheackLogin() {
    const getToken = localStorage.getItem("dlyUserToken")
    if (!getToken) {
      return true
    }
    return false
  }
  useEffect(() => {
    localStorage.setItem("contmenus", JSON.stringify(menulistData))
  }, [menulistData])
  function getconter() {
    let getconters = autoSetCounterList.filter((res) => {
      if (getouterConter.discountType !== "" && getouterConter.status !== "") {
        return (
          res.discountType == getouterConter.discountType &&
          res.status == getouterConter.status
        )
      }

      if (getouterConter.discountType !== "") {
        return res.discountType == getouterConter.discountType
      }
      if (getouterConter.status !== "") {
        return res.status == getouterConter.status
      }

      return true
    })
    if (selectMunu == "all") {
      return getconters
    }
    return getconters.filter((res) => res.selectMenuConter == selectMunu)
  }
  const cunpRunSleKeys: any = {
    // columnTitle: (
    //     <Space direction="vertical" size={1}>
    //         <Checkbox indeterminate={indeterminateGoders} checked={selectAllConter} onChange={(e) => {
    //             // console.log('e', e.target.checked)
    //             // console.log('goodsListData', goodsListData)
    //             setSelectAllConter(e.target.checked)
    //             if (e.target.checked) {
    //                 onSelectGoodsKeysChange(goodsListData.filter(res => res.chrackData.check_pass).map((item: any) => {
    //                     return item.product_id
    //                 }))
    //             } else {
    //                 onSelectGoodsKeysChange([])
    //             }
    //         }}></Checkbox>
    //         <span>{selectGoodsKeys.length}/{goodsListData.length}</span>
    //     </Space>
    // ),
    // columnWidth: 100,
    selectedRowKeys: selecteCOnterKeys,
    onChange: (e) => {
      // console.log('e', e)
      setSelecteCOnterKeys([...e])
    }
    // getCheckboxProps: (record) => ({
    //     disabled: !record.chrackData.check_pass
    // }),
  }
  const [getouterConter, setouterConter] = useState({
    status: "",
    discountType: ""
  })
  const [shearContertDta, setShearContertData] = useState({
    status: "",
    discountType: ""
  })

  const [showLoginBox, setShowLoginBox] = useState(cheackLogin())
  function cheackLoginfatyer(show = false) {
    // console.log('addnewPrd', addnewPrd)
    if (!addnewPrd) {
      if (!show) {
        Modal.warning({
          title: "提示",
          content: (
            <>
              插件版本过旧无法使用请前往官网
              <Button
                type="link"
                onClick={(e) => {
                  open("https://doulingyang.cn")
                }}>
                doulingyang.cn
              </Button>
              下载最新版本后刷新页面使用！！
            </>
          ),
          okText: "知道了",
          centered: false
        })
        return false
      }
      return false
    }
    // console.log('isBuyStatus.status', isBuyStatus)
    if (isBuyStatus.status) {
      if (!show) {
        Modal.confirm({
          title: isBuyStatus.title,
          content: isBuyStatus.content,
          icon: null,
          okText: isBuyStatus.okText,
          cancelText: " 取消",
          onOk: () => {
            open(isBuyStatus.url)
            return
          }
        })
        return false
      }

      return false
    }
    // console.log('cheackLogin()', cheackLogin())
    if (cheackLogin()) {
      if (!show) {
        Modal.warning({
          title: "提示",
          content: "请先登录后使用插件",
          okText: "前往登录",
          onOk: () => {
            setShowLoginBox(true)
          }
          // centered: false,
        })
        return false
      }
      return false
    }
    return true
  }
  const [useTutorial, setUseTutorial] = useState(false)
  const [smsoptionsbox, setSmsoptionsbox] = useState(false)
  return (
    <div className="autoSetCoupon copyConfigBox">
      <div className="couter">
        <Form layout="inline" size="small">
          <Form.Item label="状态">
            <Select
              value={shearContertDta.status}
              disabled={!cheackLoginfatyer(true)}
              size="small"
              style={{
                width: "100px"
              }}
              onChange={(e: any) => {
                setShearContertData({ ...shearContertDta, status: e })
              }}>
              <Select.Option value={""}>全部</Select.Option>
              <Select.Option value={0}>未开始</Select.Option>
              <Select.Option value={1}>进行中</Select.Option>
              <Select.Option value={2}>已完成</Select.Option>
              <Select.Option value={3}>失败</Select.Option>
              <Select.Option value={7}>等待</Select.Option>
              <Select.Option value={6}>部分完成</Select.Option>
              <Select.Option value={9}>部分进行</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="优惠券类型">
            <Select
              value={shearContertDta.discountType}
              disabled={!cheackLoginfatyer(true)}
              size="small"
              style={{
                width: "100px"
              }}
              onChange={(e: any) => {
                setShearContertData({ ...shearContertDta, discountType: e })
              }}>
              <Select.Option value={""}>全部</Select.Option>
              <Select.Option value={1}>立减</Select.Option>
              <Select.Option value={2}>满减</Select.Option>
              <Select.Option value={3}>折扣</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item label="">
            <Space>
              <Button
                size="mini"
                type="primary"
                onClick={() => {
                  // getShearContertData()
                  if (!cheackLoginfatyer()) return
                  setouterConter({ ...shearContertDta })
                }}>
                筛选
              </Button>
              <Button
                size="mini"
                onClick={() => {
                  if (!cheackLoginfatyer()) return
                  setouterConter({
                    status: "",
                    discountType: ""
                  })
                  setShearContertData({
                    status: "",
                    discountType: ""
                  })
                }}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
        <div className="loginconte">
          <Space>
            {!showLoginContent && (
              <Button
                size="mini"
                onClick={() => {
                  setSmsoptionsbox(true)
                  dispatch(getDlyUserInfoAction(""))
                }}>
                配置短信提醒
              </Button>
            )}
            {showLoginContent && (
              <Button
                size="mini"
                type="primary"
                onClick={() => {
                  console.log("点击了")

                  setShowLoginBox(true)
                }}>
                登陆
              </Button>
            )}
            <Button
              size="mini"
              type="primary"
              onClick={() => {
                setUseTutorial(true)
              }}>
              使用教程
            </Button>
          </Space>
        </div>
      </div>

      <div
        style={{
          height: 5
        }}></div>
      <Table
        size="small"
        scroll={{ x: 300 }}
        // style={{
        //     height: 800
        // }}
        rowKey="id"
        rowSelection={cunpRunSleKeys}
        title={(resor) => {
          return (
            <Space
              direction="vertical"
              style={{
                width: "100%"
              }}>
              <Space
                style={{
                  width: "100%",
                  justifyContent: "space-between"
                }}>
                <h4>自动设置任务列表</h4>
                <Space>
                  {/* <Button onClick={() => {
                            window.postMessage({
                                type_urs: 'relodinenv',
                            })
                        }}>刷新脚本</Button> */}
                  <Space size={4}>
                    <div>任务循环间隔</div>
                    <InputNumber
                      unit="分钟"
                      min={0.5}
                      size="small"
                      max={60}
                      // defaultValue={item.createBeforConf.useNum}
                      value={runTimeStop}
                      // width={60}
                      style={{
                        width: 60
                      }}
                      placeholder="请输入1-60的数字"
                      onChange={(e) => {
                        setRunTimeStop(e)
                        localStorage.setItem("runTimeStaturTime", e.toString())
                      }}></InputNumber>
                    {/* <Input suffix="分钟" /> */}
                    <Tooltip title="设置任务循环的间隔时长，时长过短可能会导致操作频繁，如任务无法执行或执行出现异常可尝试切换子账号后， 将该时长加大！！！">
                      <Icon type="DoubtIcon"></Icon>
                    </Tooltip>
                  </Space>
                  <Button
                    size="mini"
                    onClick={() => {
                      if (!cheackLoginfatyer()) return
                      Modal.warning({
                        title: "提示",
                        content: "确定删除选中的任务吗？",
                        onOk: () => {
                          const copySendData = JSON.parse(
                            JSON.stringify(autoSetCounterList)
                          )
                          selecteCOnterKeys.forEach((item) => {
                            const index = copySendData.findIndex(
                              (res) => res.id == item
                            )
                            if (index != -1) {
                              copySendData.splice(index, 1)
                            }
                            // copySendData.splice(item, 1)
                          })
                          setAutoSetCounterList(copySendData)
                          setSelecteCOnterKeys([])
                        }
                      })
                    }}
                    disabled={selecteCOnterKeys.length == 0}
                    type="primary"
                    danger>
                    删除选中任务
                  </Button>

                  <Popover
                    content={
                      <Space>
                        <Input
                          style={{
                            width: 200
                          }}
                          size="small"
                          placeholder="请输入分组名称"
                          value={addMunStext}
                          onChange={(e) => {
                            setAddMunStext(e.target.value)
                          }}></Input>
                        <Button
                          size="small"
                          type="primary"
                          onClick={() => {
                            setMenulistData([
                              ...menulistData,
                              {
                                name: addMunStext,
                                key:
                                  generateRandomString(8) +
                                  String(Date.now()).substr(5) +
                                  String(Math.random()).substr(2, 4)
                              }
                            ])
                            setAddMunStext("")
                            setAddConter(false)
                          }}>
                          确定
                        </Button>
                        <Button
                          size="small"
                          onClick={() => {
                            setAddMunStext("")
                            setAddConter(false)
                          }}>
                          取消
                        </Button>
                      </Space>
                    }
                    trigger="click"
                    visible={addConter}>
                    <Button
                      size="mini"
                      onClick={() => {
                        if (!cheackLoginfatyer()) return
                        setAddConter(true)
                      }}>
                      添加分组
                    </Button>
                  </Popover>

                  <Button
                    size="mini"
                    type="primary"
                    onClick={() => {
                      // const getDataList = getInfoCoupListData()
                      // aoutCoup(getDataList)
                      // 开始任务
                      if (!cheackLoginfatyer()) return
                      const getAllconfigData = autoSetCounterList.filter(
                        (item) =>
                          item.status == 0 ||
                          item.status == 7 ||
                          item.status == 6 ||
                          item.status == 9
                      )
                      if (!getAllconfigData || !getAllconfigData.length) {
                        message.warning("请先配置任务")
                        return
                      }
                      Modal.warning({
                        title: "提示",
                        content:
                          "开始任务后，请勿刷新页面或关闭页面，否则任务将无法正常执行！",
                        onOk: () => {
                          // window.onbeforeunload = function (event) {
                          //     return "您正在运行自动优惠券任务, 离开有任务将无法继续运行!!!" // 新版本浏览器不起作用
                          // }
                          autoCoupStart("")
                        }
                      })
                      // autoCoupStart('')
                    }}>
                    开始任务
                  </Button>
                  <Button
                    size="mini"
                    type="primary"
                    onClick={() => {
                      if (!cheackLoginfatyer()) return
                      setModowType("add")
                      setAddAutoCoupStatus(true)
                    }}>
                    添加任务
                  </Button>
                </Space>
              </Space>
              <Menu selectedKeys={[selectMunu]} mode="horizontal">
                {menulistData.map((item, index) => {
                  return (
                    <Menu.Item
                      key={item.key}
                      onClick={() => {
                        setSelectMenu(item.key)
                      }}>
                      <Space>
                        <span>{item.name}</span>
                        {/* 删除按钮 */}

                        {item.key !== "all" && (
                          <Button
                            style={{
                              color: "red"
                            }}
                            icon={<Icon type="DeleteIcon"></Icon>}
                            size="small"
                            type="link"
                            danger
                            onClick={() => {
                              Modal.warning({
                                title: "提示",
                                content: "确定删除吗？",
                                onOk: () => {
                                  setMenulistData([
                                    ...menulistData.filter(
                                      (items) => item.key != items.key
                                    )
                                  ])

                                  setSelectMenu("all")
                                }
                              })
                            }}></Button>
                        )}
                      </Space>
                    </Menu.Item>
                  )
                })}
                {/* <Menu.Item>全部</Menu.Item> */}
              </Menu>
            </Space>
          )
        }}
        columns={columnsAllTiles}
        dataSource={getconter()}
        pagination={undefined}></Table>
      <Modal
        visible={addAutoCoupStatus}
        title={
          <>
            {modowType === "add"
              ? "添加"
              : modowType === "copy"
              ? "复制"
              : "编辑"}
            自动优惠券配置
          </>
        }
        onOk={async () => {
          if (autoRef.current) {
            // console.log('childRef.curren', childRef.current)
            const data: any = await autoRef.current?.someMethod()
            console.log("data", autoSetCounterList)
            if (!data) return
            data.sort = autoSetCounterList.length
            if (modowType == "add" || modowType == "copy") {
              const copySendData = JSON.parse(
                JSON.stringify(autoSetCounterList)
              )
              copySendData.push(...data)
              copySendData.forEach((item, index) => {
                item.sort = index
              })
              setAutoSetCounterList(copySendData)
            }
            if (modowType == "edit" && editIndex !== -1) {
              const copySendData = JSON.parse(
                JSON.stringify(autoSetCounterList)
              )
              copySendData[editIndex] = data[0]
              setAutoSetCounterList(copySendData)
            }
            editIndex = -1
            setAddAutoCoupStatus(false)
          }
        }}
        onCancel={() => {
          setAddAutoCoupStatus(false)
          editIndex = -1
        }}
        width={1230}
        okText={
          modowType === "add" ? "添加" : modowType === "copy" ? "复制" : "编辑"
        }
        style={{
          height: "100%"
        }}
        wrapClassName={"mocconterstop"}
        destroyOnClose={true}>
        <AutoPage
          ref={autoRef}
          editConfigData={editConfigData}
          modowType={modowType}
          menulistData={menulistData}
          setMenulistData={setMenulistData}
          selectMunu={selectMunu}
          setAddMunStext={setAddMunStext}
        />
      </Modal>
      <Modal
        visible={showAutoCoupList}
        title={lockGoodsConter ? "已创建完成商品" : "任务商品"}
        onCancel={() => {
          setLockGoodsConter(false)
          setShowAutoCoupList(false)
        }}
        width={1255}
        wrapClassName={"mocconterstop"}
        destroyOnClose={true}
        mask={false}
        maskClosable={false}
        footer={
          lockGoodsConter ? null : (
            <Space>
              <Button
                type="primary"
                onClick={() => {
                  if (selectGoodsdRef.current) {
                    const getSelectGoods: any =
                      selectGoodsdRef.current?.getSelectGoods()
                    // getAlltet.getSelectGoods = getSelectGoods
                    const copySendData = JSON.parse(
                      JSON.stringify(autoSetCounterList)
                    )
                    copySendData[editIndex].getSelectGoods = getSelectGoods
                    setAutoSetCounterList(copySendData)
                  }
                  setLockGoodsConter(false)
                  setShowAutoCoupList(false)
                }}
                size="mini">
                编辑
              </Button>
              <Button
                size="mini"
                onClick={() => {
                  setLockGoodsConter(false)
                  setShowAutoCoupList(false)
                }}>
                关闭
              </Button>
            </Space>
          )
        }>
        <GoodsTable
          ref={selectGoodsdRef}
          addCouponConfig={addCouponConfig}
          couponTableDataShop={[]}
          // couponTableDataShop={couponTableDataShop}
          autoStatus={true}
          isLock={lockGoodsConter}
          selectGoodsList={
            lockGoodsConter
              ? addCouponConfig.runScususe
              : addCouponConfig.getSelectGoods
          }
          // isLock={true}
        ></GoodsTable>
      </Modal>
      <LoginDlyUser
        visible={showLoginBox}
        onCancel={() => {
          setShowLoginBox(false)
        }}
        onOk={() => {
          setShowLoginBox(false)
          setShowLoginContent(cheackLogin())
        }}
      />
      <Modal
        visible={useTutorial}
        title="自动设券视频教程"
        width={999}
        onCancel={() => {
          setUseTutorial(false)
        }}
        footer={null}
        bodyStyle={{ padding: 0 }}
        // mask={false}
        // maskClosable={false}
        // wrapClassName={'mocconterstop'}
        destroyOnClose={true}>
        <video
          style={{ width: "100%", margin: "20px auto 0" }}
          src={`${process.env.PLASMO_PUBLIC_CN_OSS}funsaction/counp/3612_1720614394.mp4`}
          controls
          autoPlay></video>
      </Modal>
      <Popover
        placement="topRight"
        content={
          <div className="imagesBox">
            <ImgDefault
              mask={false}
              borderRadius={8}
              style={{ width: 88, height: 88, margin: "0 auto 10px" }}
              // src={goodPrettify.pic}
              imgSrc={
                ossurl +
                "webimages/code/WechatIMG6.jpg?time=" +
                new Date().getTime()
              }></ImgDefault>
            <p
              style={{
                fontSize: 12
                // color: '#999',
              }}>
              扫码联系客服反馈
            </p>
          </div>
        }>
        <div
          className="codeBdoer"
          style={{
            bottom: -75
          }}>
          <Icon type="CustomerServiceIcon"></Icon>
          联系客服
        </div>
      </Popover>
      <SmsOptions
        visible={smsoptionsbox}
        onOk={() => {
          setSmsoptionsbox(false)
        }}
        onCancel={() => {
          setSmsoptionsbox(false)
        }}
      />
    </div>
  )
}

export default forwardRef(AutoSetCoupon)
